import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class RightSideView {
    public static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
        public TreeNode(int val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }
    }
    public List<Integer> rightSide(TreeNode root){
        List<Integer>result =new ArrayList<>();
        if (root == null){
            return result;
        }
        Queue<TreeNode>queue =new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            //固定下size，如果size变化下边的不走了
            int size =queue.size();
             result.add(queue.peek().val);
            for (int i = 0; i < size; i++) {
             TreeNode node = queue.poll();
             if (node.right != null){
                 queue.add(node.right);
             }
             if (node.left != null){
                 queue.add(node.left);
             }
            }
        }
        return result;
    }
    public List<Integer> rs1(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        // first time add root
        while (!queue.isEmpty()) {
            // first time size = 1
            // 第二次 size = 2(2,3)
            int size = queue.size();
            //[1,3,4]
            result.add(queue.peek().val);
            for (int i = 0; i < size; i++) {
                //第二次poll 3
                // 第二次的循环 2 poll 2
                TreeNode node = queue.poll();
                //queue -> 	4 -> 2
                // queue -> 5 -> 4
                if (node.right != null) {
                    queue.add(node.right);
                }
                //
                if (node.left != null) {
                    queue.add(node.left);
                }
            }
            // after first loop, queue -> 2 -> 3
            // 第二次循环之后5 -> 4
        }
        return result;
    }


    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        //预期结果list打印 {1，3，5}
        RightSideView rs = new RightSideView();
        List<Integer> integers = rs.rs1(root);
        System.out.println(integers);
        List<Integer> integers2 = rs.rightSide(root);
        System.out.println(integers2);
    }
}
